package com.irdstudio.basic.framework.core.util;

import com.irdstudio.basic.framework.core.constant.PubConstant;

/**
 * 
 * 提供加解密的字符串转换需求
 * 
 * @author Cytus_
 * @since 2018年5月17日 下午3:08:20
 * @version 1.0
 *
 */
public final class CrypticUtility {


    /**
     * java字节数组转换成16进制字符串
     * @param b
     * @return
     */
    public final static String byte2hex(byte[] b) { 
        String hs = "";
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            //整数转成十六进制表示
            tmp = (Integer.toHexString(b[n] & 0XFF));
            hs = tmp.length() == 1 ? hs + "0" + tmp : hs + tmp;
        }
        return hs.toUpperCase(); //转成大写

    }

    /**
     * 16进制字节数组转java字节数组
     * @param b
     * @return
     */
    public final static byte[] hex2byte(byte[] b) {
        if ((b.length % 2) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] b2 = new byte[b.length / 2];
        for (int n = 0; n < b.length; n += 2) {
            String item = new String(b, n, 2);
            b2[n / 2] = (byte) Integer.parseInt(item, 16);
        }
        return b2;
    }

    /**
         * 字符串转换成十六进制值
         * @param bin String 我们看到的要转换成十六进制的字符串
         * @return
        */
    public final static String bin2hex(String bin) {
        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs = bin.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(digital[bit]);
            bit = bs[i] & 0x0f;
            sb.append(digital[bit]);
        }
        return sb.toString();
    }

    /**
     * 十六进制转换字符串
     * @param hex String 十六进制
     * @return String 转换后的字符串
     */
    public final static String hex2bin(String hex) {
        String digital = "0123456789ABCDEF";
        char[] hex2char = hex.toCharArray();
        byte[] bytes = new byte[hex.length() / 2];
        int temp;
        for (int i = 0; i < bytes.length; i++) {
            temp = digital.indexOf(hex2char[2 * i]) * 16;
            temp += digital.indexOf(hex2char[2 * i + 1]);
            bytes[i] = (byte) (temp & 0xff);
        }
        return new String(bytes);
    }
  
    /**
     * 首先将文本转换成16进制字符串，然后再转换成字节数组进行加密
     * @param bin
     * @return
     */
    public final static byte[] getEncByteFromStr(String bin){
        try {
			return hex2byte(bin2hex(bin).getBytes(PubConstant.CHARSET_UTF_8));
		} catch (Exception e) { }
        return null;
    }
    
    /**
     * 将16进制字符串转换成字节数组进行解密
     * @param hex
     * @return
     */
    public final static byte[] getDecByteFromStr(String hex){
        try {
			return hex2byte(hex.getBytes(PubConstant.CHARSET_UTF_8));
		} catch (Exception e) { }
        return null;
    }
    
}
